<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      ref="crud"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :row-style="rowStyle"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增报检</el-button>
        <el-button type="danger" size="small" icon="el-icon-back" @click="handleRevoke" :disabled="!selectionList.length">撤销报检</el-button>
        <el-button type="success" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
        <el-button type="primary" size="small" @click="handleAddUrgent">加急</el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" size="small" icon="el-icon-view" @click="handleView(row, 'view')">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(row, 'edit')">处理</el-button>
        <el-button type="text" size="small" v-if="permission.qcWaitInspectionSheet_executeInspection" @click="handleExecuteInspection(row)">执行检验</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <!-- 撤销检验 -->
    <el-dialog append-to-body :close-on-click-modal="false" title="撤销检验" :visible.sync="revokeDialog">
      <avue-form ref="revokeForm" v-if="revokeDialog" v-model="revokeForm" :option="revokeOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="revokeSubmit"><i class="el-icon-circle-plus-outline"></i><span>提 交</span></el-button>
        <el-button size="small" @click="revokeDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <!-- 新增首件检验 -->
    <el-dialog append-to-body :close-on-click-modal="false" title="新增完工报检" :visible.sync="addDialog">
      <avue-form v-if="addDialog" ref="addForm" v-model="addForm" :option="addOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addInapection"><i class="el-icon-circle-plus-outline"></i><span>提 交</span></el-button>
        <el-button size="small" @click="addDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!--公用模态弹框-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <!--    详情-->
    <view-inspect ref="viewInspect" :visible.sync="viewVisable"></view-inspect>
    <!--处理-->
    <handleInspect ref="handleInspect" :visible.sync="handleVisable" :paramValue="paramValue" @closeDialog="handleCloseBeforeInspect"></handleInspect>
    <export-comp
      ref="exportComp"
      page-api-url="mes-product/qms-inspection-document/page?statusStr=1,4&documentType=CQC"
      :option="option"
      :page="page"
      :query="exportParams"
      file-name="完工待检"
    ></export-comp>
    <!--执行检验弹窗-->
    <el-dialog
      v-if="executeInspectionDialog"
      fullscreen
      append-to-body
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      title="执行检验"
      :visible.sync="executeInspectionDialog"
    >
      <execute-inspection :liveParams="liveParams" @closeDialog="exeInspectionCloseDialog" v-if="executeInspectionDialog" ref="executeInspection"></execute-inspection>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getOption, revokeOption, getAddOption } from './completeWaitInspect';
import { getList, getLineList, getLineListByWorkOrder, revoke, getWorkOrderDetail, add, urgent } from '@/api/quality/beforePackingWaitInspect.js';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
import { mapGetters } from 'vuex';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import viewInspect from './components/viewCompleteInspect';
import handleInspect from './components/handleCompleteInpspect';
import { getParamDetail } from '@/api/system/param';
import { filterEmptyValues } from '@/util/util';
import executeInspection from '@/views/designer/preview';
export default {
  name: 'completeWaitInspect',
  mixins: [userConfig()],
  components: {
    userTableConfig,
    viewInspect,
    handleInspect,
    exportComp,
    commonModalTemplate,
    executeInspection
  },
  data() {
    return {
      option: getOption(this),
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      liveParams: {
        documentNo: ''
      },
      executeInspectionDialog: false,
      exportParams: {},
      viewVisable: false,
      handleVisable: false,
      revokeDialog: false,
      addDialog: false,
      revokeForm: {},
      addForm: {},
      revokeOption,
      addOption: getAddOption(this),
      lineList: [],
      selectionList: [],
      data: [],
      form: {},
      query: {},
      timer: new Date().getTime(),
      tableOption: {},
      modalName: '',
      paramValue: false
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permission, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.getAllLine();
    //平野检验模板区分
    getParamDetail({
      paramKey: 'qms.plm_inpectionTemplate_config'
    }).then((res) => {
      let data = res.data.data;
      this.paramValue = this._get(data, 'paramValue') === 'false' ? false : true;
    });
  },
  methods: {
    exeInspectionCloseDialog() {
      this.executeInspectionDialog = false;
      this.onLoad(this.page);
    },
    handleExecuteInspection(row) {
      if (!row.apaasTemplateId) {
        this.$message({
          type: 'warning',
          message: `${row.partNo}（物料编码）没有配置检验模板，请先进行配置！`
        });
        return;
      }
      this.liveParams.documentNo = row.documentNo;
      this.executeInspectionDialog = true;
      this.$nextTick(() => {
        this.$refs.executeInspection.viewApaasTemplate(row.apaasTemplateId);
      });
    },
    async onLoad(page, params = {}) {
      try {
        this.loading = true;
        const baseParams = { documentType: 'CQC' };
        const res = await getList(page.currentPage, page.pageSize, Object.assign(params, this.query, baseParams));
        const data = res.data.data;
        this.page.total = data.total;
        (data.records || []).sort((a, b) => {
          if (a.isUrgent === b.isUrgent) {
            // 如果isUrgent相同，按照createTime降序排列
            return new Date(a.createTime) - new Date(b.createTime) > 0;
          } else if (a.isUrgent) {
            // 如果a.isUrgent为true，排在前面
            return -1;
          } else {
            // 如果b.isUrgent为true，排在前面
            return 1;
          }
        });
        this.data = data.records;
      } catch (e) {
      } finally {
        this.loading = false;
      }
    },
    getAllLine() {
      // const lineId = this.findObject(this.option.column, 'lineId');
      // const optionLineId = this.findObject(this.addOption.column, 'lineId');
      // getLineList().then(
      //   (res) => {
      //     this.lineList = this._get(res, 'data.data', []);
      //     lineId.dicData = this._get(res, 'data.data', []);
      //     lineId.dicData = this._map(lineId.dicData, (item) => {
      //       return {
      //         label: item.name,
      //         value: item.id
      //       };
      //     });
      //     optionLineId.dicData = lineId.dicData;
      //   },
      //   (error) => {
      //     lineId.dicData = [];
      //     optionLineId.dicData = [];
      //   }
      // );
    },
    //根据工单获取产线
    findLineName(workOrderId) {
      const optionLineId = this.findObject(this.addOption.column, 'lineId');
      getLineListByWorkOrder({ workOrderId }).then((res) => {
        this.lineList = this._get(res, 'data.data', []);
        optionLineId.dicData = this._map(this.lineList, (item) => {
          return {
            label: item.name,
            value: item.id
          };
        });
        if (this.lineList.length > 0) {
          this.addForm.lineId = this.lineList[0].id;
        }
      });
    },
    handleRevoke() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.revokeDialog = true;
      this.revokeForm = this.selectionList[0];
    },
    handleAdd() {
      this.addForm = {};
      this.addDialog = true;
    },
    revokeSubmit() {
      this.$refs.revokeForm.validate((valid, done) => {
        if (valid) {
          const data = { id: this.revokeForm.id, revocation: this.revokeForm.revocation };
          revoke(data).then((res) => {
            this.$message.success(res.data.msg);
            this.revokeDialog = false;
            this.onLoad(this.page);
          });
        }
      });
    },
    addInapection() {
      this.$refs.addForm.validate((valid, done) => {
        if (valid) {
          this.addForm['documentType'] = 'CQC';
          let line = this._find(this.lineList, { id: this.addForm.lineId });
          this.addForm['lineName'] = line ? line.name : '';
          // this.addForm['documentSubType'] = 'FQC_BEFORE_PACKING';
          this.addForm['suorceType'] = 'WORKORDER';
          if (this.documentNo) {
            let documentNos = this.documentNo.split(',');
            this.$confirm(`<p class='confirm-message-wrap'>该工单目前已存在${documentNos.length}个待检单（${this.documentNo}），是否继续报检?</p>`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            }).then(() => {
              add(this.addForm).then(
                (res) => {
                  this.addDialog = false;
                  this.$message.success(res.data.msg);
                  this.onLoad(this.page);
                  done();
                },
                (error) => {
                  done();
                }
              );
            });
          } else {
            add(this.addForm).then(
              (res) => {
                this.addDialog = false;
                this.$message.success(res.data.msg);
                this.onLoad(this.page);
                done();
              },
              (error) => {
                done();
              }
            );
          }
        }
      });
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partNoModal':
          this.query.partNo = this._get(rowData, 'partNo', '');
          break;
        case 'partnerModal':
          this.query.partnerName = this._get(rowData, 'name', '');
          break;
        case 'pageWorkOrderModal':
          this.query.sourceNo = this._get(rowData, 'orderNo', '');
          break;
        case 'addWorkOrderModal':
          this.addForm.sourceId = rowData.id || '';
          this.addForm.sourceNo = rowData.orderNo || '';
          this.addForm.workOrderQuantity = rowData.planQuantity || '';
          this.addForm.workOrderCompletedQuantity = rowData.completedQuantity || '';
          this.addForm.partnerName = rowData.partnerName || '';
          this.addForm.partnerCode = rowData.partnerCode || '';
          this.addForm.partMasterId = rowData.partMasterId || '';
          this.addForm.partNo = rowData.partNo || '';
          this.addForm.partName = rowData.partName || '';
          this.addForm.partModel = rowData.partModel || '';
          this.getWorkOrderDetail(rowData.orderNo);
          this.findLineName(rowData.id);
          break;
        case 'documentNoModel':
          this.query.documentNo = this._get(rowData, 'documentNo', '');
          break;
        default:
          break;
      }
    },

    getWorkOrderDetail(workOrderNo) {
      getWorkOrderDetail(workOrderNo, 'CQC').then((res) => {
        this.addForm.workshopId = this._get(res, 'data.data.workOrderVO.workshopId', '');
        this.addForm.workshopName = this._get(res, 'data.data.workOrderVO.workshopName', '');
        this.addForm.lotNo = this._get(res, 'data.data.workOrderVO.lotNo', '');
        this.documentNo = this._get(res, 'data.data.documentNo', '');
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowStyle({ row, column, rowIndex }) {
      if (row.isUrgent) {
        return {
          background: '#ffff00'
        };
      }
      return;
    },
    async handleAddUrgent() {
      try {
        const params = { ids: this.ids };
        await urgent(params);
        this.$message.success('操作成功');
        this.onLoad(this.page);
      } catch (e) {}
    },
    handleEdit(row, type) {
      this.handleVisable = true;
      this.$refs.handleInspect.getData(row.id);
    },
    handleView(row, type) {
      this.viewVisable = true;
      this.$refs.viewInspect.getData(row.id);
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    // 物料编码
    openPartModal() {
      this.modalName = 'partNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '物料数据（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '产品型号',
            prop: 'partModel'
          }
        ]
      };
    },
    openPartnerModal() {
      this.modalName = 'partnerModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择客户信息（双击进行选择）',
        url: '/api/mes-admin/customer/page',
        isPage: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        rowSelectionType: 'single',
        titleInfo: 'partnerInfo',
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    handleCloseBeforeInspect() {
      this.onLoad(this.page);
    },
    openWorkOrderCommonModal(type) {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = type;
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page?statusStr=2,3',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    openDocumentNoModel() {
      this.modalName = 'documentNoModel';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择检验单号（双击进行选择）',
        url: '/api/mes-product/qms-inspection-document/page?statusStr=1,4&document_type=CQC',
        isPage: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'sourceNo'
          },
          {
            label: '客户名称',
            prop: 'partnerName'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          }
        ]
      };
    },
    handleExport() {
      this.exportParams = Object.assign(filterEmptyValues(this.query), { documentType: 'CQC', statusStr: '1,4' });
      this.$refs.exportComp.visible = true;
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-table__body tr.current-row > td {
  background-color: transparent;
}
</style>
<style lang="scss">
.confirm-message-wrap {
  word-wrap: break-word;
}
</style>
